/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;

import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Configuration;

import android.widget.Toast;
import android.os.BatteryManager;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.net.Uri;
import android.database.Cursor;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;

public class AppActivity extends Cocos2dxActivity {
	// 先定义一个静态变量 app 用于接收 this。
	private static AppActivity app = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }
        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.getInstance().init(this);
		// 先添加这一句
		app = this;
		if(app.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            app.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }
    //简单交互-提示字符串
	public static String getTestText () {
		return "我是 Java 返回的字符串！";
	}
	//显示弹窗文字
    public static void showToast (final String string) {
		app.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(app, string, Toast.LENGTH_LONG).show();
			}
		});
	}
	//显示Android 原生的 Alert 对话框
	public static void showAlertDialog(final String title,final String message) {
        // 这里一定要使用 runOnUiThread
        app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog alertDialog = new AlertDialog.Builder(app).create();
                alertDialog.setTitle(title);
                alertDialog.setMessage(message);
                //alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();
            }
        });
    }	
	
	//获取电池信息
    public static String getElect() {
		// 参数：电池信息改变时
		IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		Intent receiver = app.registerReceiver(null, filter);
		// 利用 getIntExtra 获取信息
		int level = receiver.getIntExtra("level", 0);    //获取当前电量
		int scale = receiver.getIntExtra("scale", 0);    //获取总电量
		int status = receiver.getIntExtra("status", 0);  //获取充电状态
		int voltage = receiver.getIntExtra("voltage", 0);//获取电压(mv)
		// 电池状态
		String batteryStatus = "";
		switch (status) {
			case BatteryManager.BATTERY_STATUS_UNKNOWN:
				batteryStatus = "[没有安装电池]";
				break;
			case BatteryManager.BATTERY_STATUS_CHARGING:
				batteryStatus = "[正在充电]";
				break;
			case BatteryManager.BATTERY_STATUS_FULL:
				batteryStatus = "[已经充满]";
				break;
			case BatteryManager.BATTERY_STATUS_DISCHARGING:
				batteryStatus = "[放电中]";
				break;
			case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
				batteryStatus = "[未充电]";
				break;
			default:
				batteryStatus = "[未知状态]";
				break;
		}
		// 将信息拼接成 xx,xx,xx,xx 的形式
		StringBuilder info = new StringBuilder();
		info.append(level);
		info.append(",");
		info.append(scale);
		info.append(",");
		info.append(batteryStatus);
		info.append(",");
		info.append(voltage);
		return info.toString(); 
	}

	//调起相册
	public static void getImgData () {
		Intent intent_album = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		app.startActivityForResult(intent_album, 2);
	}	
    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
        SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SDKWrapper.getInstance().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        SDKWrapper.getInstance().onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKWrapper.getInstance().onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
		//调取相册图片添加的代码
		if (data != null) {
			// 得到图片的全路径写法，可以copy
			Uri uri = data.getData();
			String[] filePathColumns = { MediaStore.Images.Media.DATA };
			Cursor c = getContentResolver().query(uri, filePathColumns, null, null, null);
			//修复
			/* String imagePath;
			if(c != null){
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				String picturePath = c.getString(columnIndex);
				c.close();
				imagePath = picturePath;
			}else{
				imagePath = uri.getPath();
			} */
			c.moveToFirst();
			int columnIndex = c.getColumnIndex(filePathColumns[0]);
			String imagePath = c.getString(columnIndex);
			// 获取后显示下图片路径
			Toast.makeText(app, imagePath, Toast.LENGTH_LONG).show();
			// 根据路径读取图片来获取下图片宽高
			Bitmap srcBmp = BitmapFactory.decodeFile(imagePath);
			int w = srcBmp.getWidth();
			int h = srcBmp.getHeight();
			// 拼接执行语句 cc.showImg("imagePath", "w", "h")
			//在执行 Cocos2dxJavascriptJavaBridge.evalString 时要在 GL 线程中，
			//而且其中变量要用 “\”” 这种写法包上
			final StringBuilder evalString = new StringBuilder();
			evalString.append("cc.showImg(\"");
			evalString.append(imagePath);
			evalString.append("\",\"");
			evalString.append(w);
			evalString.append("\",\"");
			evalString.append(h);
			evalString.append("\")");
			app.runOnGLThread(new Runnable() {
				@Override
				public void run() {
					Cocos2dxJavascriptJavaBridge.evalString(evalString.toString());
				}
			});
		}
			
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SDKWrapper.getInstance().onNewIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKWrapper.getInstance().onStop();
    }
        
    @Override
    public void onBackPressed() {
        SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        SDKWrapper.getInstance().onStart();
        super.onStart();
    }
}
